package cn.tedu.note.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tedu.note.dao.NoteDao;
import cn.tedu.note.dao.NotebookDao;
import cn.tedu.note.dao.UserDao;
import cn.tedu.note.entity.Notebook;
import cn.tedu.note.entity.User;


@Service("notebookService")
public class NotebookServiceImpl 
	implements NotebookService{
	@Resource
	private NotebookDao notebookDao;
	@Resource
	private UserDao userDao;
	
	@Transactional
	public List<Map<String, Object>> 
		listNotebooks(String userId) 
		throws UserNotFoundException {
		
		if(userId==null || 
			userId.trim().isEmpty()){
			throw new UserNotFoundException(
					"User ID 不能空");
		}
		User user=
			userDao.findUserById(userId);
		if(user==null){
			throw new UserNotFoundException("用户不存在");
		}
		return notebookDao
			.findNotebooksByUserId(userId);
	}
	
	@Resource 
	private NoteService noteService;
	
	@Transactional
	public int deleteNotebooks(String... ary){
		for (String id : ary) {
			//0. 如果没有笔记本 则抛出异常
			Notebook book=notebookDao
					.findNotebookById(id);
			if(book==null){
				throw new NotebookNotFoundException("ID:"+id);
			}
			//1. 找的笔记本中全部的笔记ID
			List<Map<String, Object>> list=
					noteService.listNotes(id);
			String[] idList=new String[list.size()];
			int i=0; 
			for(Map<String, Object> map:list){
				idList[i++]=(String)map.get("id");
			}
			//2. 删除这些笔记
			noteService.deleteNotes(idList);
			//3. 删除这个笔记本
			notebookDao.deleteNotebookById(id);
		}
		return 0;
	}
	
	public List<Map<String, Object>> 
		listNotebooks(String userId, 
		int pageNum) 
		throws UserNotFoundException {
		if(userId==null||userId.trim().isEmpty()){
			throw new UserNotFoundException("ID空");
		}
		User user=userDao.findUserById(userId);
		if(user==null){
			throw new UserNotFoundException("User不存在");
		}
		int size=6;
		int start=pageNum*size;
		Map<String, Object> param=
			new HashMap<String, Object>();
		param.put("tableName", "cn_notebook");
		param.put("userId", userId);
		param.put("start", start);
		param.put("rows", size);
		return notebookDao
			.findNotebooksByParam(param);
	}
}



